<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//当函数不存在的时候才去创建
if (!function_exists('randstr')) {
    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    function randstr($len = 8, $special=false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
    
        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }
    
        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++)
        {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

// 上传单个文件
function upload($name="images"){
    // 获取表单上传文件
    $file=request()->file($name);

    if($file){
        $info=$file->validate(['ext'=>'jpg,jpeg,png,gif'])
                ->move(ROOT_PATH.'public'.DS.'uploads');

        // 判断是否上传成功
        if($info){
            // 返回路径+文件名
            return str_replace("\\","/",$info->getSaveName());
        } 
    }
    return false;
}

// 上传多个文件
function uploads($name='images'){
    $file=request()->file($name);

    foreach($file as $files){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $files->validate(['ext'=>'jpg,jpeg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');

        if($info){
            $data[] = '/uploads/'.$info -> getSaveName();

            // 返回路径+文件名
            return str_replace("\\","/",$data);
        } 
    }
    return false;
}

// $to 收件人的地址
// $msg 收件内容
function send($to,$msg=''){
    // var_dump(APP_PATH.'phpmail/class.phpmailer.php');
    // var_dump(is_file(APP_PATH.'phpmail/class.phpmailer.php'));
    // exit;
    //引入邮件发送的类
    // APP_PATH TP常量 application
    include_once(APP_PATH.'phpmail/class.phpmailer.php');

    // 实例化这个邮箱类
    $mail=new PHPMailer(true);

    // 设置发送的协议 smtp
    $mail->IsSMTP();

    // 是否验证
    $mail->SMTPAuth=true;

    // 设置端口
    $mail->Port=25;

    // 设置第三方服务
    $mail->Host="smtp.163.com";

    // 设置第三方的账号密码 密码不是登录密码，是授权密码
    $mail->Username="j1965245366@163.com";
    $mail->Password="kk66058";

    // 回复人
    $mail->AddReplyTo("j1965245366@163.com","雨欣汉服官方");

    $mail->From       = "j1965245366@163.com";  //发件人地址
	$mail->FromName   = "雨欣汉服官方";	//发件人名称

    // 添加收件人
    $mail->AddAddress($to);

    $mail->Subject  = "雨欣汉服邮箱认证"; //邮件主题

    // 设置多少个字符换行 80字符
    $mail->WordWrap=80;

    $mail->MsgHTML($msg);//发送的内容

    // 发送的内容里面是否允许发送带HTML的
    $mail->IsHTML(true);

    // 成功发送返回true 失败返回false
    return $mail->Send();
}

// 创建一个公共函数，来处理评论的递归 处理数据
function CommentTree($list,$pid=0,$User){
    $data=[];

    if($list){
        foreach($list as $item){
            if(!empty($item['like'])){
                // 字符串转换为数组
                $LikeArr=explode(',',$item['like']);
                $LikeArr=array_filter($LikeArr);//去除数组中的空元素
                $LikeCount=is_array($LikeArr) ? count($LikeArr) : 0;

                $item['like_count']=$LikeCount;

                // 判断当前这一条评论是不是本人点过赞
                if(in_array($User['id'],$LikeArr)){
                    $item['active']=true;
                }else{
                    $item['active']=false;
                }
            }else{
                // 当like字段为空时
                $item['like_count']=0;
            }

            // id=1 pid=0
            if($item['pid'] == $pid){
                // 找出相等pid值，给当前的评论新增一个自定义属性
                // 递归找子集
                $item['child']=CommentTree($list,$item['id'],$User);
                $data[]=$item;
            }
        }
    }
    return $data;
}

// 处理递归循环输出 处理输出
function CommentHtml($list,$post,$flag='top',$output=""){
    foreach($list as $key=>$item){
        // 外边距
        $PaddingLeft=$item['level']*3;

        $output .= "<li style='padding-left: {$PaddingLeft}em' class='jieda-daan'>";
            $output .= "<div class='detail-about detail-about-reply'>";
                // 头像
                $url = url('home/user/index',['userid'=>$item['userid']]);
                $output .= "<a class='fly-avatar' href='$url'>";

                    // 判断头像
                    if(is_file($item['user']['avatar'])){
                        $avatar=$item['user']['avatar'];
                        $output .= "<img src='/$avatar' />";
                    }else{
                        $output .= "<img src='/assets/home/images/avatar.jpg' />";
                    }

                $output .= "</a>";

                // 用户信息
                $output .= "<div class='fly-detail-user'>";
                    // 昵称
                    $output .= "<a href='javascript:void(0)' class='fly-link'>";
                        $nickname=$item['user']['nickname'];
                        $output .= "<cite>$nickname</cite>";

                        if($item['user']['auth'] > 0){
                            $output .= "<i class='iconfont icon-renzheng'></i>";
                        }
                    $output .= "</a>";

                    // 楼主
                    if($key == 0 && $flag == 'top'){
                        $output .= "<span style='color: #FF7200;'>(楼主)</span>";
                    }

                    // 判断是否为发帖人
                    if($item['userid'] == $post['userid']){
                        $output .= "<span style='color:#5FB878'>(发帖人)</span>";
                    }
                $output .= "</div>";

                // 评论时间
                $output .= "<div class='detail-hits'>";
                    $output .= "<span>{$item['createtime']}</span>";
                $output .= "</div>";

                // 采纳图标
                if($item['accept'] == 1){
                    $output .= "<i class='iconfont icon-caina' title='最佳答案'></i>";
                }
            $output .= "</div>";

            // 评论内容
            $output .= "<div class='detail-body jieda-body photos'>";
                $output .= "<p>{$item['content']}</p>";
            $output .= "</div>";

            // 回复
            if(cookie('LoginUser')){
                $output .= "<div class='jieda-reply'>";
                    // 点赞
                    if(isset($item['active'])){
                        $output .= "<span class='jieda-zan zanok like' type='zan' data-commentid=".$item['id'].">";
                    }else{
                        $output .= "<span class='jieda-zan like' type='zan' data-commentid=".$item['id'].">";
                    }
                    $output .= "<i class='iconfont icon-zan'></i>";
                    $output .= "<em>{$item['like_count']}</em>";
                    $output .= "</span>";

                    // 回复
                    if(!$post['accept']){
                        $pid = $item['id'];
                        $nickname2 = $item['user']['nickname'];
                        $output .= "<a href='#comment' class='reply' data-pid='$pid' data-nickname='$nickname2' type='reply'>";
                            $output .= "<i class='iconfont icon-svgmoban53'></i>\r\n回复";
                        $output .= "</a>";
                    }
                    $output .= "<div class='jieda-admin'>";
                        // (登录的人  == 发帖userid)发帖人 || 评论本人(评论人 == 登录的人)
                        $userid = cookie('LoginUser')['id'];
                        if($userid == $post['userid'] || $userid == $item['userid']){
                            if(!$post['accept']){
                                $output .= "<span type='del' class='CommentDel' data-commentid='{$item['id']}'>删除</span>";
                            }
                        }

                        if($userid == $post['userid']){
                            if(!$post['accept']){
                                $output .= "<span class='accept' data-comid='{$item['id']}' class='jieda-accept' type='accept'>";
                                    $output .= "采纳";
                                $output .= "</span>";
                            }
                        }
                    $output .= "</div>";
                $output .= "</div>";
            }
        $output .= "</li>";

        // 判断是否有子集
        if(!empty($item['child'])){
            $output = CommentHtml($item['child'],$post,'son',$output);
        }
    }
    return $output;
}

// 删除评论
function DelComment($comid, $data = []){
    // 一级评论
     $list = model('Post.Comment')->where('pid',$comid)->column('id');

     if($list)
     {
        // $data[] = $list;
        // return $data;
        foreach($list as $item)
        {
            $data[] = $item;

            $child = model('Post.Comment')->where('pid',$item)->find();

            if($child)
            {
                $data = DelComment($item, $data);
            }
        }
     }

     return $data;
}

//定义一个获取连续签到次数的方法
/**
 * $arr 需要循环的数组数据
 * $num 记录连续签到多少天
 * $tbegin 今天的开始时间戳
 * $today 今天是否已签到
 */
function moreSign($arr,$num,$tbegin,$today){
    if($today){
        foreach($arr as $key=>$item){
            if($item['createtimenum'] > $tbegin-86400*$num && $item['createtimenum'] < $tbegin-86400*($num-1)){
                return moreSign($arr,$num+1,$tbegin,$today);
            }else if(($key+1 == count($arr)) && ($item['createtimenum'] < $tbegin-86400*$num || $item['createtimenum'] > $tbegin-86400*($num-1))){
                return $num;
            }
        }
    }else{
        foreach($arr as $key=>$item){
            if($item['createtimenum'] > $tbegin-86400*($num+1) && $item['createtimenum'] < $tbegin-86400*$num){
                return moreSign($arr,$num+1,$tbegin,$today);
            }else if(($key+1 == count($arr)) && ($item['createtimenum'] < $tbegin-86400*($num+1) || $item['createtimenum'] > $tbegin-86400*$num)){
                return $num;
            }
        }
    }
}


// 按每月的增加量统计
/**
 * $time 数据的创建时间createtime字段
 * $count 要统计的条件，默认为查所有
 * $table 要统计的数据表
 * $Array 定义一个空数组的变量名
 */
use Think\Db;
function Monthcount($time,$count='*',$table)
{
    $sql=Db::query("select distinct(from_unixtime(".$time.",'%Y-%m')) as month,count(".$count.") as monthcount from ".$table." group by month");

    $x=date('m');
    $y=date('Y');
    $xData=[];
    for($i=0;$i<12;$i++){
        // $xData[]=date($y.'-'.$x.'-01');//每个月的第一天
        if($x<10){
            $xData[]=date($y.'-0'.$x);
        }else{
            $xData[]=date($y.'-'.$x);
        }
        
        $x--;
        if($x<1){
            $x=12;
            $y--;
        }
        // 数据逆转排序
        array_multisort($xData);
    }

    $Array=[];
    if(!empty($sql)){
        foreach($xData as $key=>$item){
            foreach($sql as $k=>$v){
                if($item == $v['month']){
                    $Array[$key]=$v['monthcount'];
                    break;
                }else{
                    $Array[$key]=0;
                    continue;
                }
            }
        }
    }else{
        foreach($xData as $key=>$item){
            $Array[$key]=0;
        }
    }

    // array_multisort($Array);
    return $Array;
}


if (!function_exists('build_code')) {

    /**
     * 生成唯一订单号
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix.$order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}